<template>
  <Page title="错题本">
    <template #navBarCustom>
      <NewBar
        title="错题本"
        :tabs="subjects.list"
        :usedSubject="subjects.usedSubject"
        :moreSubject="subjects.moreSubject"
        :active="subjects.active"
        @change="subjects.onChange($event)"
      >
        <template #rightBtn>
          <div class="item2 flex items-center" @click="search">
            <img class="icon mr-6px" src="static/icons/camera-white.png" mode="" />
            <span class="name text-white">拍照添加错题</span>
          </div>
        </template>
      </NewBar>
    </template>
    <template #content>
      <div class="w-full h-full p-20px box-border box-border flex flex-col">
        <!-- 知识点列表弹窗 -->
        <div class="dialog-wrap" v-show="isShowKpointDialog">
          <div class="kpoint-dialog flex flex-col bg-white px-84px py-30px relative">
            <div class="header">
              <img
                class="close absolute"
                src="static/icons/close.png"
                mode=""
                @click="isShowKpointDialog = false"
              />
              <div class="w-full title text-center text-262A30 font-medium mb-20px">
                选择知识点
              </div>
            </div>
            <el-input v-model="filters.kpointKeyword" class="mb-20px" placeholder="搜索知识点" />
            <div class="flex-1 list text-333 font-medium overflow-scroll">
              <div
                v-for="(i, index) in kpoints"
                :key="index"
                class="item"
                :class="i.id === filters.kpointId ? 'text-51C3FF' : ''"
                @click="filters.changeKPointId(i.id)"
              >
                {{ i.name }}
              </div>
            </div>
          </div>
        </div>
        <div class="main flex-1 flex overflow-hidden">
          <div class="filters h-full box-border bg-white">
            <div class="w-full h-full overflow-scroll split_line">
              <div
                class="label mb-31px"
                @click="isShowKpointDialog = true"
                v-if="!isEnglishSubject"
              >
                <img class="newIcon" src="@/assets/wqbook/zs@2x.png" alt="" />
                <div>知识点：</div>
                <div class="flex-1">
                  <span class="text-51C3FF">{{ choseKPointName }}</span>
                </div>
              </div>

              <div class="label text-A3A3A3 font-normal mb-6px">
                <img class="newIcon" src="@/assets/wqbook/clock@2x.png" alt="" />
                <span>时间</span>
                <img
                  class="dirIcon"
                  v-show="controlOff.time"
                  src="@/assets/wqbook/down@2x.png"
                  @click="controlOff.time = !controlOff.time"
                  alt=""
                />
                <img
                  class="dirIcon"
                  v-show="!controlOff.time"
                  src="@/assets/wqbook/up@2x.png"
                  @click="controlOff.time = !controlOff.time"
                  alt=""
                />
              </div>
              <div class="mt-10px flex items-center flex-wrap" v-show="controlOff.time">
                <div
                  class="option"
                  :class="option.name === filters.timeRangeValue ? 'active-option' : ''"
                  @click="filters.changeTimeRange(option.type)"
                  v-for="(option, index) in filters.timeRangeList"
                  :key="index"
                >
                  {{ option.name }}
                </div>
              </div>

              <div class="label text-A3A3A3 font-normal mb-6px">
                <img class="newIcon" src="@/assets/wqbook/tx@2x.png" alt="" />
                <span>题型</span>
                <img
                  class="dirIcon"
                  v-show="controlOff.qtype"
                  src="@/assets/wqbook/down@2x.png"
                  @click="controlOff.qtype = !controlOff.qtype"
                  alt=""
                />
                <img
                  class="dirIcon"
                  v-show="!controlOff.qtype"
                  src="@/assets/wqbook/up@2x.png"
                  @click="controlOff.qtype = !controlOff.qtype"
                  alt=""
                />
              </div>
              <div class="mt-10px flex items-center flex-wrap" v-show="controlOff.qtype">
                <div
                  class="option"
                  :class="option.typeName === filters.typeName ? 'active-option' : ''"
                  @click="filters.changeTypeName(option.typeName)"
                  v-for="(option, index) in filters.typeIdList"
                  :key="index"
                >
                  {{ option.typeName }}
                </div>
              </div>

              <div class="label text-A3A3A3 font-normal mb-6px">
                <img class="newIcon" src="@/assets/wqbook/nd@2x.png" alt="" />
                <span>难度</span>
                <img
                  class="dirIcon"
                  v-show="controlOff.diffcult"
                  src="@/assets/wqbook/down@2x.png"
                  @click="controlOff.diffcult = !controlOff.diffcult"
                  alt=""
                />
                <img
                  class="dirIcon"
                  v-show="!controlOff.diffcult"
                  src="@/assets/wqbook/up@2x.png"
                  @click="controlOff.diffcult = !controlOff.diffcult"
                  alt=""
                />
              </div>
              <div class="mt-10px flex items-center flex-wrap" v-show="controlOff.diffcult">
                <div
                  class="option"
                  :class="option.value === filters.difficultyLevel ? 'active-option' : ''"
                  @click="filters.changeDifficultyLevel(option.value)"
                  v-for="(option, index) in filters.difficultyLevelList"
                  :key="index"
                >
                  {{ option.name }}
                </div>
              </div>

              <!-- 重置 -->
              <div class="reset flex items-center" @click="filters.reset()">
                <img class="icon mr-12px" src="static/icons/reset.png" mode="" />
                <span class="text text-333">重置筛选条件</span>
              </div>
            </div>
          </div>
          <div class="list h-full box-border bg-white" style="font-size: 0.24rem">
            <!-- 学科网 -->
            <QuestionListXkw :questions="questions" v-if="!isEnglishSubject" />
            <!-- 英语听说 -->
            <QuestionListEnglish :questions="questions" v-else />
          </div>
        </div>
        <div class="bottom"></div>
      </div>
    </template>
  </Page>
</template>

<script>
import Page from '@/components/page/newPage'
import SubjectTabs from '@/components/subject/tabs'
import NewBar from '@/components/subject/tabs/newTabs'
import QuestionListXkw from './components/question-list-xkw/index'
import QuestionListEnglish from './components/question-list-english/index'
import {
  getSubjectApi,
  getQuestionTypeApi,
  getWrongQuestionBookPageApi,
  searchQuestionsByImageApi,
  updateSearchQuestionsTime,
  deleteWqBookApi,
  getKpointApi,
  getSimilarRecommend,
  wrongBookRecordApi,
  createRecommendUseRecord
} from '@/api/wq-book'
import { checkStudyClockinApi } from '@/api/daily-attendance'
import { debounce, uploadImage } from '@/utils'
import { MODULE_ID } from '@/store/modules/module-use'
import { mapActions } from 'vuex'
export default {
  components: {
    Page,
    SubjectTabs,
    QuestionListXkw,
    QuestionListEnglish,
    NewBar
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      if (from.name === 'redirect') return

      vm.questions.reset()
      vm.questions.getList()
    })
  },
  data() {
    return {
      recordId: '',
      timeout: null,
      isShowKpointDialog: false,
      controlOff: {
        time: true,
        qtype: true,
        diffcult: false
      },
      // 学科栏目
      subjects: {
        vm: this._self,
        active: undefined,
        list: [],
        getList: async function (callback) {
          const { data = [] } = await getSubjectApi()
          const subjects = await this.vm.getDictByType('subject')
          this.usedSubject = subjects.filter((item) => {
            return ['1', '2', '3', '4', '5'].includes(item.value)
          })
          // this.usedSubject.unshift({
          //   value: '',
          //   label: '全部'
          // })
          this.moreSubject = subjects.filter((item) => {
            return !['1', '2', '3', '4', '5'].includes(item.value)
          })
          // 如果没有开通的科目，弹出弹窗
          if (data.length === 0) {
            this.vm.$popup.show({
              type: 'alert',
              success: (popup) => {
                popup.$on('confirm', () => {
                  this.vm.$popup.hide('alert')
                  this.vm.$router.back()
                })
                popup.setData({
                  content: '没有已开通的科目'
                })
              }
            })
            return
          }

          this.list = data
            .map((i, index) => {
              if (index === 0) {
                this.active = i.subjectId
              }

              return {
                dictType: 'subject',
                label: i.subjectName,
                status: 0,
                value: i.subjectId
              }
            })
            .filter((i) => !!i)

          callback(this.list.length ? this.list[0].value : '')
        },
        onChange: debounce(async function (subjectId) {
          // 上传模块使用时间
          this.vm.$store.state.moduleUse.currentModuleUse.submit()
          // 重置
          this.vm.$store.state.moduleUse.currentModuleUse.onSubjectChange(subjectId)

          this.vm.recordLeave()
          this.vm.recordEnter(subjectId)
          // 知识点
          this.vm.filters.kpointKeyword = ''
          const { data: kPointList } = await getKpointApi({
            subjectId
          })
          this.vm.filters.kpointId = undefined
          this.vm.filters.kpointList = kPointList
          // 题型
          const { data: typeIdList } = await getQuestionTypeApi({
            subjectId
          })
          typeIdList.unshift({
            typeName: '全部',
            typeId: undefined
          })
          this.vm.filters.typeName = '全部'
          this.vm.filters.typeIdList = typeIdList
          this.active = subjectId
          // 问题列表
          this.vm.questions.reset()
          this.vm.questions.getList()
        }, 300)
      },
      filters: {
        vm: this._self,
        startTime: undefined,
        endTime: undefined,
        timeRangeValue: '全部',
        timeRangeList: [
          {
            name: '全部',
            type: 'all'
          },
          {
            name: '近7天',
            type: '7'
          },
          {
            name: '近30天',
            type: '30'
          },
          {
            name: '近60天',
            type: '60'
          }
        ],
        changeTimeRange: function (type = '') {
          const today = new Date().getTime()
          switch (type) {
            case 'all':
              this.timeRangeValue = '全部'
              this.startTime = undefined
              this.endTime = undefined
              this.vm.questions.reset()
              this.vm.questions.getList()
              //全部
              break
            case '7':
              // 近7天
              this.timeRangeValue = '近7天'
              const beforeSevenDay = today - 86400000 * 7
              this.startTime = this.vm.$utils.formatTimeStamp(beforeSevenDay)
              this.endTime = this.vm.$utils.formatTimeStamp(today)
              this.vm.questions.reset()
              this.vm.questions.getList()
              break
            case '30':
              // 近30天
              this.timeRangeValue = '近30天'
              const beforeThirtyDay = today - 86400000 * 30
              this.startTime = this.vm.$utils.formatTimeStamp(beforeThirtyDay)
              this.endTime = this.vm.$utils.formatTimeStamp(today)
              this.vm.questions.reset()
              this.vm.questions.getList()
              break
            case '60':
              // 近60天
              this.timeRangeValue = '近60天'
              const beforeSixtyDay = today - 86400000 * 60
              this.startTime = this.vm.$utils.formatTimeStamp(beforeSixtyDay)
              this.endTime = this.vm.$utils.formatTimeStamp(today)
              this.vm.questions.reset()
              this.vm.questions.getList()
              break
            default:
              break
          }
        },
        kpointId: undefined,
        kpointKeyword: '',
        kpointList: [],
        changeKPointId: function (val) {
          this.kpointId = val
          this.vm.isShowKpointDialog = false
          this.vm.questions.reset()
          this.vm.questions.getList()
        },
        typeName: undefined,
        typeIdList: [],
        changeTypeName: function (value) {
          this.typeName = value
          this.vm.questions.reset()
          this.vm.questions.getList()
        },
        difficultyLevel: undefined,
        difficultyLevelList: [
          {
            name: '全部',
            value: undefined
          },
          {
            name: '容易',
            value: '17'
          },
          {
            name: '较易',
            value: '18'
          },
          {
            name: '适中',
            value: '19'
          },
          {
            name: '较难',
            value: '20'
          },
          {
            name: '困难',
            value: '21'
          }
        ],
        changeDifficultyLevel: function (value) {
          this.difficultyLevel = value
          this.vm.questions.reset()
          this.vm.questions.getList()
        },
        reset: function () {
          this.timeRangeValue = '全部'
          this.startTime = undefined
          this.endTime = undefined
          this.kpointId = undefined
          this.typeName = '全部'
          this.difficultyLevel = undefined
          this.vm.questions.reset()
          this.vm.questions.getList()
        }
      },
      questions: {
        vm: this._self,
        pageNo: 1,
        pageSize: 10,
        loading: false,
        hasMore: true,
        list: [],
        getList: debounce(async function () {
          if (this.loading) return

          this.loading = true
          const questions = this.list

          let params = {
            pageNo: this.pageNo,
            pageSize: this.pageSize,
            subject: this.vm.subjects.active,
            startTime: this.vm.filters.startTime,
            endTime: this.vm.filters.endTime,
            kpointId: this.vm.filters.kpointId,
            typeName: this.vm.filters.typeName === '全部' ? undefined : this.vm.filters.typeName,
            difficultyLevel: this.vm.filters.difficultyLevel
          }

          const {
            data: { list, total }
          } = await getWrongQuestionBookPageApi(JSON.parse(JSON.stringify(params)))

          if (list.length < this.pageSize) {
            this.hasMore = false
          }

          if (list.length > 0) {
            questions.push(
              ...list.map((i) => {
                i['isShowExplanation'] = false
                i['isCreatedBySelf'] = RegExp(/^((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+/).test(
                  i.stem
                )
                return i
              })
            )
            this.pageNo++
            this.vm.$nextTick(() => {
              MathJye.LayOut(document.body)
            })
          }

          this.loading = false
        }, 300),
        reset: function () {
          this.pageNo = 1
          this.pageSize = 10
          this.loading = false
          this.hasMore = true
          this.list = []
        },
        edit: function (item) {
          const { stem, questionId, explanation } = item
          this.vm.$store.commit('setWqBookEditingQuestion', item)
          this.vm.$router.push('/pages/wq-book/edit/index')
        },
        uploadExplanation: function (item) {
          const { questionId, explanation } = item

          this.vm.$store.commit('setWqBookEditingQuestion', item)

          if (explanation) {
            this.vm.$router.push('/pages/wq-book/explanation/show/index')
          } else {
            this.vm.$router.push('/pages/wq-book/explanation/upload/index')
          }
        },
        recommend: async function (item) {
          const { subject, questionId, kpointIdList } = item

          // 加载动画
          const loading = this.vm.$loading({
            lock: true,
            text: '加载中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.5)'
          })
          // 一分钟内加载不成功关闭loading弹窗
          const timer = setTimeout(() => {
            loading.close()
          }, 60000)

          // 获取打卡任务详情ID列表
          const { data: detailIds } = await checkStudyClockinApi({
            subjectId: subject,
            kpointIds: kpointIdList.join(','),
            type: 1
          })
          const { data, msg } = await getSimilarRecommend({
            subjectId: subject,
            questionId,
            detailIds: detailIds.map((item) => item.id)
          })

          if (!data) {
            // 关闭加载动画
            clearTimeout(timer)
            loading.close()
            this.vm.$message.error(msg)
            return
          }

          const { data: recommendUseRecordId } = await createRecommendUseRecord({
            subjectId: subject
          })

          // 关闭加载动画
          clearTimeout(timer)
          loading.close()

          const { practiceId } = data

          this.vm.$store.commit('setCurrentPractice', {
            record: {
              id: practiceId,
              subject,
              questionId,
              practiceName: '举一反三',
              userKpointDataId: 0,
              recommendUseRecordId,
              kpointIds: kpointIdList
            },
            questions: [data],
            questionIndex: 0
          })

          this.vm.$router.push('/pages/exercise/practice/xkw/index')
        },
        remove: function (id) {
          this.vm.$popup.show({
            type: 'confirm',
            success: (popup) => {
              popup.$on('cancel', () => {
                this.vm.$popup.hide('confirm')
              })
              popup.$on('confirm', async () => {
                this.vm.$popup.hide('confirm')

                // 加载动画
                const loading = this.vm.$loading({
                  lock: true,
                  text: '加载中...',
                  spinner: 'el-icon-loading',
                  background: 'rgba(0, 0, 0, 0.5)'
                })
                // 一分钟内加载不成功关闭loading弹窗
                const timer = setTimeout(() => {
                  loading.close()
                }, 60000)

                const { data: success } = await deleteWqBookApi(id)

                // 关闭加载动画
                clearTimeout(timer)
                loading.close()

                if (success) {
                  this.vm.$message.success('移出成功')
                  this.reset()
                  this.getList()
                }
              })
              popup.setData({
                content: '确认移出？'
              })
            }
          })
        }
      }
    }
  },
  computed: {
    kpoints() {
      if (this.filters.kpointList.length === 0) return []

      return this.filters.kpointList
        .map((k) => {
          if (!!this.filters.kpointKeyword && k.name.indexOf(this.filters.kpointKeyword) === -1) {
            return null
          } else {
            return k
          }
        })
        .filter((s) => !!s)
    },
    choseKPointName() {
      if (!this.filters.kpointId) return '全部>>'

      return this.filters.kpointList.find((k) => k.id === this.filters.kpointId).name
    },
    isEnglishSubject() {
      if (this.subjects.active === '66') {
        return true
      } else {
        return false
      }
    }
  },
  created() {
    this.subjects.getList(async (subjectId) => {
      // 初始化模块使用记录
      this.$store.commit('setCurrentModuleUse', {
        vm: this._self,
        type: MODULE_ID.WQ_BOOK,
        subjectId
      })

      if (!subjectId) {
        return
      }

      this.recordEnter(subjectId)
      this.questions.getList()
      // 知识点
      const { data: kPointList } = await getKpointApi({
        subjectId: this.subjects.active
      })
      this.filters.kpointList = kPointList
      // 题型
      const { data: typeIdList } = await getQuestionTypeApi({
        subjectId
      })
      typeIdList.unshift({
        typeName: '全部',
        typeId: undefined
      })
      this.filters.typeName = '全部'
      this.filters.typeIdList = typeIdList
    })
  },
  mounted() {},
  beforeDestroy() {
    if (this.timeout) clearTimeout(this.timeout)

    this.recordLeave()
  },
  methods: {
    ...mapActions(['getDictByType']),
    // 记录进入错题本
    recordEnter(subjectId) {
      if (this.timeout) clearTimeout(this.timeout)
      this.timeout = setTimeout(async () => {
        const { data: id } = await wrongBookRecordApi({
          method: 0,
          subjectId
        })
        if (id) {
          this.recordId = id
        }
      }, 60000)
    },
    // 记录退出错题本
    recordLeave() {
      if (this.recordId) {
        wrongBookRecordApi({
          method: 1,
          id: this.recordId
        })
      }
    },
    search() {
      this.$popup.show({
        type: 'alert',
        success: (popup) => {
          popup.$on('confirm', async () => {
            this.$popup.hide('alert')
            const { android_call } = window

            if (!android_call || !window.android) {
              const res = await uploadImage()
              let imageBase64 = res
              const {
                code,
                data = null,
                msg: searchQuestionId
              } = await searchQuestionsByImageApi({
                imageBase64: imageBase64.replace('data:image/png;base64,', '')
              })

              if (code == 0 && data.length > 0) {
                this.$store.commit('setSearchQuestionId', searchQuestionId)
                this.$store.commit('setWqBookSearchedQuestion', data)
                this.$router.push('/pages/wq-book/search/index')
              } else {
                if (!Number.isNaN(parseInt(searchQuestionId))) {
                  await updateSearchQuestionsTime({
                    searchQuestionId,
                    studentDuration: 0
                  })
                }
                this.$store.commit('setWqBookEditingQuestion', {
                  stem: imageBase64
                })
                this.$router.push('/pages/wq-book/edit/index')
              }
            } else {
              const callback = async (base64) => {
                const imageBase64 = 'data:image/png;base64,' + base64
                const {
                  code,
                  data = null,
                  msg: searchQuestionId
                } = await searchQuestionsByImageApi({
                  imageBase64
                })

                if (code == 0 && data.length > 0) {
                  this.$store.commit('setSearchQuestionId', searchQuestionId)
                  this.$store.commit('setWqBookSearchedQuestion', data)
                  this.$router.push('/pages/wq-book/search/index')
                } else {
                  if (!Number.isNaN(parseInt(searchQuestionId))) {
                    await updateSearchQuestionsTime({
                      searchQuestionId,
                      studentDuration: 0
                    })
                  }
                  this.$store.commit('setWqBookEditingQuestion', {
                    stem: imageBase64
                  })
                  this.$router.push('/pages/wq-book/edit/index')
                }
              }

              const callBackName = `fn${new Date().getTime()}`
              window.android_call[callBackName] = callback.bind(this)

              android.takePhoto(callBackName)
            }
          })
          popup.setData({
            confirmText: '我知道了',
            title: '温馨提示',
            content:
              '搜题照片将记录于老师后台，请勿用于抄作业等行为，否则老师有权停用拍照搜题功能！'
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.item2 {
  position: absolute;
  top: 0;
  right: 20px;
  // width: 200px;
  height: 100%;
  align-items: center;
  justify-content: center;
  .icon {
    width: 34px;
    height: 34px;
  }

  .name {
    font-size: 26px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
.main {
  width: 100%;
  .filters {
    width: 344px;
    .split_line {
      border-right: 1px solid rgba(232, 232, 232, 1);
      box-sizing: border-box;
      padding-right: 10px;
    }
    .label {
      font-size: 26px;
      font-weight: 500;
      color: rgba(51, 51, 51, 1);
      display: flex;
      align-items: center;
      line-height: 26px;
      margin-bottom: 32px;
      .newIcon {
        width: 26px;
        height: 26px;
        margin-right: 6px;
      }
      .dirIcon {
        width: 20px;
        height: 20px;
        margin-left: 6px;
      }
    }
    .option {
      font-size: 24px;
      text-align: center;
      min-width: 102px;
      height: 46px;
      background-color: rgba(246, 246, 246, 1);
      border-radius: 35px;
      display: flex;
      justify-content: center;
      flex-wrap: wrap;
      align-items: center;
      margin-right: 9px;
      white-space: nowrap;
      margin-bottom: 10px;
      box-sizing: border-box;
      &:last-child {
        margin-right: 0px;
      }
    }
    .active-option {
      color: #51c3ff;
      background: #eef9ff;
      opacity: 1;
      border: 1px solid #51c3ff;
    }

    .reset {
      margin-top: 31px;
      .icon {
        width: 44px;
        height: 44px;
      }

      .text {
        font-size: 22px;
      }
    }
  }

  .list {
    width: calc(100% - 344px);
    padding-left: 20px;
    box-sizing: border-box;
  }
}

.dialog-wrap {
  width: 100vw;
  height: 100vh;
  background: rgba($color: #000000, $alpha: 0.5);
  position: absolute;
  left: 0;
  top: 0;
  z-index: 1999;

  .kpoint-dialog {
    width: 567px;
    height: 500px;
    border-radius: 16px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);

    .close {
      width: 16px;
      height: 16px;
      top: 16px;
      right: 16px;
    }

    .header {
      .title {
        font-size: 22px;
        line-height: 30px;
      }
    }

    .list {
      font-size: 20px;
      line-height: 28px;

      .item {
        &:not(:first-child) {
          margin-top: 8px;
        }
      }
    }
  }
}

/deep/ .uni-searchbar {
  padding: 0;
}

/deep/ .uni-searchbar__box {
  padding: 0;
  background-color: #fff !important;
  border: 1px solid #d9d9d9;
  height: 44px;
}
</style>
